var express = require('express'),
    http = require('http'),
    socket = require('socket.io'),
    app = express(),
    io,
    log = console.log,
    sessid,
    allUsers = {};

app.configure(function(){
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
    app.use(express.favicon());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser('your secret here'));
    app.use(express.session());
    app.use(express.static(__dirname + '/static'));
});

app.configure('development', function(){
    app.use(express.errorHandler());
});

app.get('/', function (req, res) {
    res.sendfile(__dirname + '/index.html');
});

var server = http.createServer(app).listen(app.get('port'), function(){
    log('Express server listening on port ' + app.get('port'));
});

io = socket.listen(server, { log: false });
io.set('authorization', function(handshakeData, callback) {
    handshakeData.sessid = getCookie(handshakeData.headers.cookie, 'connect.sid');
    callback(null, true);
});
io.sockets.on('connection', function (socket) {
    socket.on('afterconnected', function(username) {
        sessid = socket.handshake.sessid;
        allUsers[sessid] = username;
        socket.emit('user list', allUsers);
        socket.broadcast.emit('user list', allUsers);
        socket.broadcast.emit('user connected', username);
    }).on('disconnect', function() {
        sessid = socket.handshake.sessid;
        var username = allUsers[sessid];
        socket.broadcast.emit('afterdisconnect', username);
        delete allUsers[sessid];log(username, sessid, allUsers);
    }).on('message', function(data) {
        socket.broadcast.emit('public message', data);
        socket.emit('public message', data);
    });
});

function getCookie(cookieStr, name) {
    var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'),
    arr = cookieStr.match(reg);

    return arr ? arr[2] : '';
}